package com.tomcov.client.activities;


import com.google.gwt.activity.shared.AbstractActivity;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.place.shared.Place;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AcceptsOneWidget;
import com.tomcov.client.ClientFactory;
import com.tomcov.client.place.LicencePlace;
import com.tomcov.client.service.UserServiceAsync;
import com.tomcov.client.view.CreatUserView;
import com.tomcov.shared.UserInfo;

public class CreatUserActivity extends AbstractActivity implements CreatUserView.Presenter{

	private ClientFactory clientFactory;

	public CreatUserActivity(ClientFactory clientFactory){
		this.clientFactory = clientFactory;	
	}

	@Override
	public void start(AcceptsOneWidget panel, EventBus eventBus) {
		CreatUserView creatUserView = clientFactory.getCreatUserView();
		creatUserView.getNextButton().addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				creatUser();
			}
		});
		creatUserView.setPresenter(this);
		panel.setWidget(creatUserView.asWidget());
	}

	@Override
	public void goTo(Place place) {
		clientFactory.getPlaceController().goTo(place);			
	}

	public void creatUser(){
		CreatUserView creatuserview= clientFactory.getCreatUserView();
		UserServiceAsync USA = clientFactory.getUSA();
		if(creatuserview.getUserName()==null||creatuserview.getFirstName()==null||creatuserview.getLastName()==null
				||creatuserview.getAdressEmail()==null||creatuserview.getPassword()==null){
			Window.alert("fill all the field");
		}
		else{	
			UserInfo user= new UserInfo(creatuserview.getUserName(),creatuserview.getFirstName(),creatuserview.getLastName(),creatuserview.getAdressEmail(),creatuserview.getPassword());
			USA.addUser(user,new AsyncCallback<UserInfo>(){
				@Override
				public void onFailure(Throwable caught) {
					Window.alert("server failed");

				}
				@Override
				public void onSuccess(UserInfo result) {
					if (result==null){
						Window.alert("this name is already used");
					}
					else{
						Window.alert("user created");
						goTo(new LicencePlace(null));	
					}

				}
			});
		}

	}
}